package com.sxp.servlet;

import com.sxp.bean.Book;
import com.sxp.bean.Cart;
import com.sxp.bean.User;
import com.sxp.dao.BookDao;
import com.sxp.dao.CartDao;
import com.sxp.dao.impl.BookDaoImpl;
import com.sxp.dao.impl.CartDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author hsowan
 * @date 2019-06-14
 **/
@WebServlet("/cart/add")
public class AddCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int bookId = Integer.valueOf(req.getParameter("bookid"));

        HttpSession session = req.getSession();

        User user = (User) session.getAttribute("user");

        if (user != null) {
            BookDao bookDao = new BookDaoImpl();
            Book book = bookDao.getById(bookId);

            if (book.getStock() > 0) {
                int userId = user.getId();

                CartDao cartDao = new CartDaoImpl();
                Cart cart = cartDao.getByBookIdAndUserId(bookId, userId);



                if (cart != null) {
                    cart.setAmount(cart.getAmount() + 1);
                    cartDao.update(cart);
                }else {
                    cartDao.save(new Cart(bookId, userId, book.getName(), book.getPrice()));
                }

                book.setStock(book.getStock() - 1);
                bookDao.update(book);

                session.setAttribute("msg", "添加成功！");
                resp.sendRedirect("/obs/message.jsp");
            } else {
                session.setAttribute("msg", "库存不足！");
                resp.sendRedirect("/obs/message.jsp");
            }
        } else {

        }
    }
}
